<template>
  <!-- main-container -->
  <!-- 主容器 -->
  <div class="nav-container page-component">
    <!-- 左侧导航 -->
    <div class="nav left-nav">
      <div class="nav-item ">
        <span class="v-link clickable dark"
              :onclick="'javascript:window.location=\'/hospital/'+hospital.hoscode+'\''">预约挂号 </span>
      </div>
      <div class="nav-item selected">
        <span class="v-link selected dark"
              :onclick="'javascript:window.location=\'/hospital/ai/'+hospital.hoscode+'\''"> 智能导诊 </span>
      </div>
      <div class="nav-item ">
        <span class="v-link clickable dark"
              :onclick="'javascript:window.location=\'/hospital/detail/'+hospital.hoscode+'\''"> 医院详情 </span>
      </div>
      <div class="nav-item">
        <span class="v-link clickable dark"
              :onclick="'javascript:window.location=\'/hospital/notice/'+hospital.hoscode+'\''"> 预约须知 </span>
      </div>
      <div class="nav-item">
        <span class="v-link clickable dark">停诊信息</span>
      </div>
      <div class="nav-item">
        <span class="v-link clickable dark">查询/取消</span>
      </div>
    </div> <!-- left-nav 结束 -->

    <!-- 右侧内容 -->
    <div class="right-main">
      <!-- 头部 -->
      <div class="header">
        <span class="title">AI 聊天式问诊</span>
      </div>

      <!-- content-wrapper -->
      <!-- 聊天主体 -->
      <div class="chat-container">
        <!-- 对话区 -->
        <div class="chat-main">
          <el-card class="dialog-card">
            <div class="dialog-history">
              <div v-for="(message, index) in messages"
                   :key="index"
                   class="message-item"
                   :class="{'ai-message': message.sender === 'AI', 'user-message': message.sender === 'User'}">

                <!-- 头像 -->
                <div class="message-avatar">
                  <el-avatar :src="getAvatarSrc(message.sender)"/>
                </div>

                <!-- 内容区 -->
                <el-card class="message-content">
                  <VueMarkdown
                    :source="message.text"
                    class="markdown-content"
                    :class="message.sender"/>

                  <!-- AI问题按钮 -->
                  <el-row v-if="message.sender === 'AI'" class="question-btns">
                    <el-button
                      v-for="(question, idx) in formattedGenerateMessage.questions"
                      :key="idx"
                      size="mini"
                      @click="handleQuestionClick(question)">
                      {{ question }}
                    </el-button>
                  </el-row>
                </el-card>
              </div> <!-- message-item 结束 -->
            </div> <!-- dialog-history 结束 -->
            <!-- 新增 el-descriptions 组件 -->
            <div v-show="showDetails">
              <el-divider>诊断建议</el-divider>
              <el-descriptions :column="2" class="margin-top" title="AI诊断结果" direction="vertical">
                <el-descriptions-item label="初步诊断建议">{{ formattedMessage.possibleCause }}</el-descriptions-item>
                <el-descriptions-item label="健康建议">{{ formattedMessage.suggestedTests }}</el-descriptions-item>
                <el-descriptions-item label="推荐项目">{{ formattedMessage.suggestedProject }}</el-descriptions-item>
                <el-descriptions-item :span="2" label="挂号科室">{{ formattedMessage.department }}</el-descriptions-item>
                <el-descriptions-item label="挂号推荐程度">
                  <el-rate
                    v-model="formattedMessage.level"
                    :texts="recommendationTexts"
                    show-text
                    disabled
                  />
                  <span style="margin-left: 10px;">{{ getRecommendation(formattedMessage.level) }}</span>
                </el-descriptions-item>
              </el-descriptions>
            </div>

            <div v-show="showDetails">
              <el-descriptions :column="4" class="margin-top" title="" direction="vertical" style="white-space:pre-wrap;">
                <el-descriptions-item label="药物推荐">{{ formattedMessage.recommendedDrug }}</el-descriptions-item>
              </el-descriptions>
            </div>
            <!-- 新增推荐科室展示部分 -->
            <div v-show="showDetails">
              <el-divider>推荐科室</el-divider>
              <el-table :data="formattedMessage.departmentList" style="width: 100%">
                <el-table-column prop="bigname" label="大科室名称" width="150"/>
                <el-table-column prop="depname" label="科室名称" width="200"/>
                <el-table-column prop="intro" label="科室介绍"/>
                <el-table-column label="操作" width="120">
                  <template slot-scope="scope">
                    <el-button type="primary" size="small" @click="schedule(scope.row.hoscode, scope.row.depcode)">一键挂号</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card> <!-- dialog-card 结束 -->

          <!-- 输入区 -->
          <div class="input-section">
            <el-form @submit.native.prevent="sendMessage">
              <el-input
                v-model="userMessage"
                type="textarea"
                :rows="3"
                placeholder="请描述您的症状（例如：头痛三天，伴有发热）"/>

              <div class="action-btns">
                <el-button
                  :loading="isLoading"
                  type="primary"
                  native-type="submit">
                  发送消息
                </el-button>
                <el-button
                  :loading="isDiagnosisLoading"
                  type="success"
                  @click="getDiagnosis">
                  获取诊断
                </el-button>
              </div>
            </el-form>
          </div> <!-- input-section 结束 -->
        </div> <!-- chat-main 结束 -->
      </div> <!-- chat-container 结束 -->
    </div> <!-- right-main 结束 -->
  </div> <!-- main-container 结束 -->
</template>
<script>
import '~/assets/css/hospital_personal.css'
import '~/assets/css/hospital.css'
import ai from '@/api/ai'
import hospitalApi from '@/api/hospital'
import VueMarkdown from 'vue-markdown'
import cookie from 'js-cookie'
import userInfoApi from '@/api/userInfo'
export default {
  components: {VueMarkdown},
  data() {
    return {
      userMessage: '',
      messages: [
        {
          sender: 'AI',
          text: `您好！我是您的健康助手，很高兴能为您服务。<br><br>` +
            `为了给您提供最恰当的帮助，请尽可能详细地告诉我您遇到了什么症状或问题。比如：<br>` +
            `- 症状首次出现的时间<br>` +
            `- 是否有规律性或特定的触发因素<br>` +
            `- 是否伴随其他不适感<br><br>` +
            `任何细节都将有助于我们进行更准确的分析。如果您不确定从哪里开始，请随时告诉我，我们会一步步来。`
        }
      ],
      showDetails: false, // 控制是否显示详细的AI诊断结果
      formattedMessage: {}, // 存储格式化后的AI响应信息
      formattedGenerateMessage: {}, // 存储格式化后的AI响应信息
      isLoading: false, // 添加这个属性来跟踪发送按钮的加载状态\
      recommendations: {
        1: '观察等待 - 病情轻微，不需要立即就医。',
        2: '预约门诊 - 病情较为轻微，建议尽快预约普通门诊。',
        3: '优先就诊 - 病情可能较为复杂，建议尽早安排时间就诊。',
        4: '尽快就医 - 病情较急，可能存在潜在风险，应尽快前往医院。',
        5: '立即急诊 - 病情危急，需要立即医疗救助。'
      },
      recommendationTexts: [
        '观察等待', '预约门诊', '优先就诊', '尽快就医', '立即急诊'
      ],
      isDiagnosisLoading: false, // 获取诊断结果按钮的加载状态
      hoscode: null,
      hospital: {
        param: {}
      }
    }
  },
  created() {
    this.hoscode = this.$route.params.hoscode
    this.init()
  },
  methods: {
    init() {
      hospitalApi.show(this.hoscode).then(response => {
        this.hospital = response.data.hospital
      })
    },
    schedule(hoscode, depcode) {
      // 登录判断
      // let token = cookie.get('token');
      // if (!token) {
      //   loginEvent.$emit('loginDialogEvent');
      //   return;
      // }

      // 判断认证
      userInfoApi.getUserInfo()
        .then(response => {
          let authStatus = response.data.authStatus;
          // 状态为2认证通过
          // if (!authStatus || authStatus != 2) {
          //   window.location.href = '/user';
          //   return;
          // }

          // 跳转到挂号页面
          window.location.href = '/hospital/schedule?hoscode=' + hoscode + "&depcode=" + depcode;
        })
        .catch(error => {
          console.error('获取用户信息失败:', error);
        });
    },
    sendMessage() {
      if (this.userMessage.trim()) {
        // 收集用户之前的提问
        const userPreviousQuestions = this.messages
          .filter(message => message.sender === 'User')
          .map(message => message.text)

        // 如果有诊断建议的问题也一并带上
        const diagnosticQuestions = this.formattedGenerateMessage.questions || []

        // 准备要发送的数据
        const dataToSend = {
          currentQuestion: this.userMessage,
          previousQuestions: userPreviousQuestions,
          diagnosticQuestions: diagnosticQuestions
        }
        this.isLoading = true // 在发送请求前设置为 true
        this.showDetails = false
        // 更新消息列表
        this.messages.push({sender: 'User', text: this.userMessage})

        // 发送 POST 请求到后端
        ai.generateChat(dataToSend)
          .then(response => {
            const aiResponse = response.data;
            // 格式化AI响应信息
            this.formattedGenerateMessage = {
              content: aiResponse.content,
              questions: aiResponse.questions || [] // 确保有 questions 字段

            }
            // 更新消息列表并显示详细信息
            this.messages.push({
              sender: 'AI',
              text: `${aiResponse.content}`
            })
            // this.showDetails = true // 显示详细的AI诊断结果
          })
          .catch(error => {
            console.error('Error fetching AI response:', error)
          })
          .finally(() => {
            this.userMessage = '' // 清空输入框
            this.isLoading = false // 请求完成后设置为 false
          })
      }
    },
    handleQuestionClick(question) {
      // 收集用户之前的提问
      const userPreviousQuestions = this.messages
        .filter(message => message.sender === 'User')
        .map(message => message.text)

      // 准备要发送的数据
      const dataToSend = {
        currentQuestion: question,
        previousQuestions: userPreviousQuestions,
        diagnosticQuestions: [question] // 只包含点击的问题
      }

      this.isLoading = true
      this.showDetails = false
      // 发送 POST 请求到后端
      ai.generateChat(dataToSend)
        .then(response => {
          const aiResponse = response.data
          // 更新消息列表
          this.messages.push({sender: 'User', text: question})

          // 格式化AI响应信息
          this.formattedGenerateMessage = {
            content: aiResponse.content,
            questions: aiResponse.questions || [] // 确保有 questions 字段
          }

          // 更新消息列表并显示详细信息
          this.messages.push({
            sender: 'AI',
            text: `${aiResponse.content}`
          })
          // this.showDetails = true // 显示详细的AI诊断结果
        })
        .catch(error => {
          console.error('Error sending question:', error)
        })
        .finally(() => {
          this.isLoading = false
        })
    },
    getAvatarSrc(sender) {
      if (sender === 'AI') {
        return 'src/icons/images/AI-04.svg' // 替换为实际的 AI 头像路径
      } else if (sender === 'User') {
        return 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png' // 替换为实际的用户头像路径
      }
      return '' // 默认头像路径
    },
    getRecommendation(level) {
      if (level === null || level === undefined || !this.recommendations[level]) {
        return '暂无推荐' // 如果没有选择评分，则不显示任何推荐信息
      }
      return this.recommendations[level]
    },
    getDiagnosis() {
      this.isDiagnosisLoading = true // 在发送请求前设置为 true
      // 收集用户之前的提问
      const userPreviousQuestions = this.messages
        .filter(message => message.sender === 'User')
        .map(message => message.text)
      // 如果有诊断建议的问题也一并带上
      const diagnosticQuestions = this.formattedGenerateMessage.questions || []
      // 准备要发送的数据
      const dataToSend = {
        currentQuestion: '获取诊断结果',
        previousQuestions: userPreviousQuestions,
        diagnosticQuestions: userPreviousQuestions
      }
      // 发送 POST 请求到后端
      ai.aiChat(dataToSend)
        .then(response => {
          const aiResponse = response.data
          // 格式化AI响应信息
          // 格式化AI响应信息
          this.formattedMessage = {
            possibleCause: aiResponse.possibleCause,
            suggestedTests: aiResponse.suggestedTests,
            department: aiResponse.department,
            suggestedProject: aiResponse.suggestedProject,
            recommendedDrug: aiResponse.recommendedDrug,
            level: aiResponse.level,
            departmentList: aiResponse.departmentList || []
          }
          console.log(this.formattedMessage.recommendedDrug)
          this.showDetails = true // 显示详细的AI诊断结果
        })
        .catch(error => {
          console.error('Error fetching AI response:', error)
        })
        .finally(() => {
          this.userMessage = '' // 清空输入框
          this.isDiagnosisLoading = false // 请求完成后设置为 false
        })
    }
  }
}
</script>

<style scoped>
/* 主布局样式 */
.main-container {
  display: flex;
  min-height: 100vh;
  background: #f8f9fa;
}

/* 左侧导航样式 */
.left-nav {
  width: 200px;
  background: white;
  border-right: 1px solid #e4e7ed;
  padding: 20px 0;
  box-shadow: 2px 0 6px rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  height: 100vh;
}

.nav-item {
  padding: 12px 24px;
  cursor: pointer;
  transition: all 0.3s;
  border-left: 3px solid transparent;
}

.nav-item:hover {
  background: #f5f7fa;
}

.nav-item.selected {
  border-left-color: #409EFF;
  background: #ecf5ff;
}

.v-link {
  color: #606266;
  font-size: 14px;
}

.v-link.selected {
  color: #409EFF;
  font-weight: 500;
}

/* 右侧内容样式 */
.right-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0; /* 修复flex布局溢出问题 */
}

.header {
  background: #409EFF;
  color: white;
  padding: 20px 30px;
  font-size: 18px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 10;
}

.chat-container {
  flex: 1;
  padding: 20px;
  overflow: auto;
}

/* 调整对话框高度 */
.dialog-card {
  min-height: calc(100vh - 160px);
  display: flex;
  flex-direction: column;
}

/* 保持原有消息样式 */
.message-item {
  margin: 10px 0;
  display: flex;
  align-items: flex-start;
}

.message-avatar {
  margin: 0 15px;
}

.message-content {
  max-width: 70%;
  min-width: 300px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 输入区域调整 */
.input-section {
  margin-top: auto; /* 始终保持在底部 */
  padding: 20px 0 0;
  background: white;
  position: sticky;
  bottom: 0;
}
.user-message {
  flex-direction: row-reverse;
}

.user-message .message-content {
  background: #e0dfff;
}

.action-btns {
  margin-top: 10px;
  text-align: right;
}
</style>
